package com.yunxi.controller.sys;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yunxi.base.pojo.BaseApplyLevelVO;
import com.yunxi.base.service.BaseApplyLevelDubboService;
import com.yunxi.common.config.RedisCacheService;
import com.yunxi.core.base.Constant;
import com.yunxi.core.util.HttpUtil;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.JwtUtils;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.dealer.pojo.PartnerVO;
import com.yunxi.dealer.service.PartnerDubboService;
import com.yunxi.sys.pojo.RoleUserVO;
import com.yunxi.sys.pojo.SSOCodeVO;
import com.yunxi.sys.pojo.StaffVO;
import com.yunxi.sys.pojo.UserVO;
import com.yunxi.sys.service.RoleUserDubboService;
import com.yunxi.sys.service.StaffDubboService;
import com.yunxi.sys.service.UserDubboService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/6/3.
 */
@RestController
@RequestMapping("/sso")
@Api(tags = "sys:sso", description = "SSO授权认证接口")
public class SSOAuthController {

    private static final Logger log = LoggerFactory.getLogger(SSOAuthController.class);

    @Autowired
    UserDubboService userDubboService;

    @Autowired
    private RedisCacheService rcs;
    @Autowired
    private PartnerDubboService partnerDubboService;
    @Autowired
    private StaffDubboService staffDubboService;

    @Autowired
    RoleUserDubboService roleUserDubboService;

    @Value("${client_id}")
    private String clientId;
    @Value("${client_secret}")
    private String clientSecret;
    @Value("${token_url}")
    private String tokenURL;
    @Value("${user_info_url}")
    private String userInfoURL;
    @Value("${pda_token_url}")
    private String pdaTokenUrl;
    @Value("${pda_profile_url}")
    private String pdaProfileUrl;

    @PostMapping(value = "/ssoPcAuth")
    @ApiOperation(value = "PC端认证", notes = "PC端授权认证")
    public ApiResult<LoginInfo> ssoAuth(@RequestBody SSOCodeVO ssoCode) {
        log.info(ssoCode.toString());
        Map map = new HashMap();
        String code = ssoCode.getCode();
        LoginInfo info = new LoginInfo();
        //redirecUri 前端回调地址
        String requestTokenURL = tokenURL + "?code="
                + code
                + "&client_id="
                + ssoCode.getClientId()
                + "&client_secret="
                + ssoCode.getClientSecret() + "&redirect_uri=" + ssoCode.getRedirectUri();
        String accessToken = HttpUtil.sendHttpsGet(requestTokenURL);
        log.info(accessToken);
        JSONObject jsonObject = JSON.parseObject(accessToken);
        if (String.valueOf(jsonObject.get("status")).equals("200")) {
            String token = String.valueOf(jsonObject.get("access_token"));
            //根据accessToken获取用户信息
            String requestUserInfoURL = userInfoURL + "?access_token="
                    + token;
            String reqUserString = HttpUtil.sendHttpsGet(requestUserInfoURL);
            ArrayList<String> accounts = getAccounts(reqUserString);
            String uid = accounts.get(0);
            map.put("userCode", uid);
            UserVO user = userDubboService.findUserByUserCode(map);
            if (user != null) {
                String tokenId = JwtUtils.createJWT(user.getUserId() + "", user.getUserName(), 1800000);
                map.put("token", tokenId);
                info.setToken(tokenId);
                info.setUser(user);
                info.setUserId(user.getUserId());
                info.setUserCode(user.getUserCode());
                info.setRealName(user.getRealName());
                if(user.getIsOpen().intValue()==1){
                    info.setMessage("观光模式");
                }
                //查询是否是渠道商
                PartnerVO partnerVO = partnerDubboService.getByUser(user);
                if(partnerVO!=null) {
                    info.setPartner(partnerVO);
                    info.setPartnerCode(partnerVO.getPartnerCode());
                }

                StaffVO staffVO = staffDubboService.getByUser(user);
                if(staffVO!=null) {
                    info.setStaff(staffVO);
                    if(StringUtils.isEmpty(info.getPartnerCode())){
                        info.setPartnerCode(staffVO.getPartnerCode());
                    }
                }

                List<RoleUserVO> roleList = roleUserDubboService.listByUserId(user.getUserId());
                Map map2 = new HashMap();
                map2.put("roleList",roleList);
                info.setSubMap(map2);

                rcs.set("token:" + tokenId, JSONObject.toJSONString(info), 50000);
                return ResponseUtil.ok(info);
            } else {
                return ResponseUtil.fail(400, "用户不存在");
            }
        } else {
            return ResponseUtil.fail(400, "CODE过期!");
        }

    }

    @PostMapping(value = "/ssoPdaAuth")
    @ApiOperation(value = "PDA认证", notes = "PDA授权认证")
    public ApiResult<LoginInfo> ssoPdaAuth(String userCode, String passWord) {
        Map map = new HashMap();
        map.put("userCode", String.valueOf(userCode));
        LoginInfo info = new LoginInfo();
        UserVO user = userDubboService.findPdaUserByUserCode(map);
        if (user != null) {
            String tokenId = JwtUtils.createJWT(user.getUserId() + "", user.getUserName(), 1800000);
            map.put("token", tokenId);
            info.setToken(tokenId);
            info.setUser(user);
            info.setUserId(user.getUserId());
            info.setUserCode(user.getUserCode());
            info.setRealName(user.getRealName());
            if(user.getIsOpen().intValue()==1){
                info.setMessage("观光模式");
            }
            //查询是否是渠道商
            PartnerVO partnerVO = partnerDubboService.getByUser(user);
            if(partnerVO!=null) {
                info.setPartner(partnerVO);
                info.setPartnerCode(partnerVO.getPartnerCode());
            }

            StaffVO staffVO = staffDubboService.getByUser(user);
            if(staffVO!=null) {
                info.setStaff(staffVO);
                if(StringUtils.isEmpty(info.getPartnerCode())){
                    info.setPartnerCode(staffVO.getPartnerCode());
                }
            }

            List<RoleUserVO> roleList = roleUserDubboService.listByUserId(user.getUserId());
            Map map2 = new HashMap();
            map2.put("roleList",roleList);
            info.setSubMap(map2);

            rcs.set("token:" + tokenId, JSONObject.toJSONString(info), 50000);
            return ResponseUtil.ok(info);
        } else {
            return ResponseUtil.fail(400, "用户不存在");
        }
      /*  Map map = new HashMap();
        String requestTokenURL = pdaTokenUrl + "?username="
                + userCode
                + "&client_id="
                + clientId
                + "&client_secret="
                + clientSecret + "&password=" + passWord;
        String accessToken = HttpUtil.sendHttpsGet(requestTokenURL);
        JSONObject jsonObject = JSON.parseObject(accessToken);
        if (String.valueOf(jsonObject.get("status")).equals("200")) {
            String token = String.valueOf(jsonObject.get("access_token"));
            String requestUserInfoURL = pdaProfileUrl + "?access_token="
                    + token
                    + "&client_id="
                    + clientId
                    + "&client_secret="
                    + clientSecret;
            String reqUserString = HttpUtil.sendHttpsGet(requestUserInfoURL);
            JSONObject userObject = JSON.parseObject(reqUserString);
            if (!String.valueOf(userObject.get("status")).equals("200")) {
                return ResponseUtil.fail(400, "token失效!");
            }
            map.put("userCode", String.valueOf(userObject.get("id")));
            LoginInfo info = new LoginInfo();
            UserVO user = userDubboService.findUserByUserCode(map);
             if (user != null) {
                String tokenId = JwtUtils.createJWT(user.getUserId() + "", user.getUserName(), 1800000);
                map.put("token", tokenId);
                info.setToken(tokenId);
                info.setUser(user);
                info.setUserId(user.getUserId());
                info.setUserCode(user.getUserCode());
                info.setRealName(user.getRealName());
                if(user.getIsOpen().intValue()==1){
                    info.setMessage("观光模式");
                }
                //查询是否是渠道商
                PartnerVO partnerVO = partnerDubboService.getByUser(user);
                if(partnerVO!=null) {
                    info.setPartner(partnerVO);
                    info.setPartnerCode(partnerVO.getPartnerCode());
                }

                StaffVO staffVO = staffDubboService.getByUser(user);
                if(staffVO!=null) {
                    info.setStaff(staffVO);
                    if(StringUtils.isEmpty(info.getPartnerCode())){
                        info.setPartnerCode(staffVO.getPartnerCode());
                    }
                }

                List<RoleUserVO> roleList = roleUserDubboService.listByUserId(user.getUserId());
                Map map2 = new HashMap();
                map2.put("roleList",roleList);
                info.setSubMap(map2);

                BaseApplyLevelVO baseApplyLevelVO = new BaseApplyLevelVO();
                baseApplyLevelVO.setBusId(Constant.PMS_VERIFY_RETUR_VEHICLE);
                baseApplyLevelVO.setUserCode(user.getUserCode());
                List<BaseApplyLevelVO> baseApplyLevelVOList = baseApplyLevelDubboService.listByVo(baseApplyLevelVO);
                if(baseApplyLevelVOList != null && baseApplyLevelVOList.size() > 0){
                    info.setCurrentLevel(baseApplyLevelVOList.get(0).getCurrentLevel());
                }

                rcs.set("token:" + tokenId, JSONObject.toJSONString(info), 50000);
                return ResponseUtil.ok(info);
            } else {
                return ResponseUtil.fail(400, "用户不存在");
            }
        } else {
            return ResponseUtil.fail(400, "账号密码不正确!");
        }*/
    }

    private ArrayList<String> getAccounts(String jsonStr) {
        ArrayList<String> accounts = new ArrayList<String>();
        //String str = "{\"id\":\"zhangsan\",\"attributes\":[{\"userAccounts\":[\"zhangsan\",\"zhangsan1\"]}]}";
        JSONObject obj = JSONObject.parseObject(jsonStr);
        JSONArray attributes = obj.getJSONArray("attributes");
        JSONObject userAccounts = (JSONObject) attributes.get(0);
        JSONArray jsonUsers = userAccounts.getJSONArray("userAccounts");
        if (jsonUsers != null && jsonUsers.size() > 0) {
            for (int i = 0; i < jsonUsers.size(); i++) {
                accounts.add(jsonUsers.getString(i));
            }
        } else {
            accounts.add((String) obj.get("id"));
        }
        return accounts;
    }

}

